<template>
	<div class="pb-15">
		<div class="text-t-3 flex items-center">
			<base-icon class="text-[14px]" name="hint" />
			<span class="ml-1">{{ $t('account.third.info') }}</span>
		</div>
		<div class="flex items-center justify-between pt-5">
			<div>
				<p class="text-[14px] text-t-1 app-font-bold flex items-center">
					<base-image src="account/google.svg" />
					<span class="py-2 ml-2">{{ $t('login.google') }}</span>
				</p>
				<p class="text-t-3 text-[12px] pl-7">
					{{ isBindGoogle ? googleInfo.email : $t('account.third.unBind') }}
				</p>
			</div>
			<base-button
				v-if="!isBindGoogle"
				@click="handleClick('google')"
				textT="account.third.bind"
				size="small"
				class="w-[68px]"
				type="primary"
				:block="false" />
		</div>
	</div>
</template>
<script lang="ts" setup>
import { computed } from 'vue'
import { BaseIcon, BaseButton, BaseImage } from '@/components/base'
import { useProfileStore, useAccountStore } from '@/store'
import { HTTP_CODES } from '@/constants'
import { useMessage } from '@/hooks'
import { bindauth } from '@/api/profile'

const message = useMessage()
const profileStore = useProfileStore()
const accountStore = useAccountStore()

const userInfoThird = computed(() => profileStore.userInfo?.third)

const googleInfo = computed(() => userInfoThird.value?.find((item) => item.provider === 'google'))

const isBindGoogle = computed(() => googleInfo.value?.providerId)

// 暂不考虑解绑逻辑，只有绑定，那么每次就要获取google token
const handleClick = async (provider: string) => {
	try {
		const data = {
			provider,
			token: ''
		}
		await accountStore.getThirdToken(provider)
		data.token = accountStore.thirdToken
		const result = await bindauth(data)
		feedback(result)
		await profileStore.getUserInfo()
	} catch (error: any) {
		if (error.code === HTTP_CODES.ThirdPartyAccountExist) {
			// showError(error)
			message.error(error)
			await accountStore.logoutThird()
		} else {
			message.error()
		}
	}
}

const feedback = (result: any) => {
	if (result.code === HTTP_CODES.Success) {
		message.success()
	} else {
		message.error()
	}
}
</script>
